package network;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import bbqtorrent.Bdecoder;
import bbqtorrent.BeValue;
import bbqtorrent.InvalidBEncodingException;

public class TrackerManager {	
	private ArrayList<Tracker> trackers;

	public TrackerManager() {		
		this.trackers = new ArrayList<Tracker>();
	}

	public TrackerManager(String url) {
		this();

		this.trackers.add(new Tracker(url));
	}

	public TrackerManager(ArrayList<String> urls) {
		this();

		for(String url : urls) {
			this.trackers.add(new Tracker(url));
		}
	}

	public boolean sendRequest(String request) {
		boolean state = true;			

		for(Tracker tracker : this.trackers) {
			try {
				URL url = new URL(tracker.getUrl()+request);
				URLConnection con = url.openConnection();     

				int len = con.getContentLength();
				System.out.println("Content-Length: " + len);
				if (len > 0) {            
					InputStream input = con.getInputStream();	            
					byte[] buffer = new byte[len];
					input.read(buffer);           

					Bdecoder bdecoder = new Bdecoder(new ByteArrayInputStream(buffer));    				
					BeValue result = bdecoder.bdecode();
					Map map = result.getMap();
					System.out.println(result);
					input.close();

					Set keys = map.keySet();
					Collection values = map.values();
					Iterator<String> iterKey = keys.iterator();	
					Iterator<BeValue> iterValue = values.iterator();
					String key = "";
					BeValue value = null;

					while(iterKey.hasNext() && iterValue.hasNext()) {
						key = iterKey.next();
						value = iterValue.next();				

						this.handle(tracker, key, value);
					}
				} else {
					state = false;
				}

			} catch(IOException e) {
				state = false;
			} catch(InvalidBEncodingException e) {
				state = false;
			}
		}

		return state;
	}

	private void handle(Tracker tracker, String key, BeValue value) throws InvalidBEncodingException {
		if(key.equals("complete")) {
			int complete = value.getInt();
		} else if(key.equals("incomplete")) {
			int incomplete = value.getInt();
		} else if(key.equals("tracker id")) {
			String trackerId = value.getString();
		} else if(key.equals("interval")) {
			int interval = value.getInt();
		} else if(key.equals("peers")) {
			byte[] peersBuffer = value.getBytes();

			if(peersBuffer.length%6==0) {
				byte[] ipBuffer = new byte[4];
				byte[] portBuffer = new byte[2];

				String ipPeer = "";
				int portPeer = -1;

				for(int i=0; i<peersBuffer.length; i+=6) {								
					System.arraycopy(peersBuffer, i, ipBuffer, 0, 4);
					System.arraycopy(peersBuffer, i+4, portBuffer, 0, 2);

					ByteBuffer bb = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);								

					ipPeer = "";
					bb.put(0, ipBuffer[0]); 
					ipPeer+=bb.order(ByteOrder.LITTLE_ENDIAN).getInt(0)+".";

					bb.put(0, ipBuffer[1]);                
					ipPeer+=bb.order(ByteOrder.LITTLE_ENDIAN).getInt(0)+".";

					bb.put(0, ipBuffer[2]);                
					ipPeer+=bb.order(ByteOrder.LITTLE_ENDIAN).getInt(0)+".";

					bb.put(0, ipBuffer[3]);                
					ipPeer+=bb.order(ByteOrder.LITTLE_ENDIAN).getInt(0);				                

					portPeer = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN)
					.put(portBuffer)
					.order(ByteOrder.LITTLE_ENDIAN)
					.getInt(0);

					System.out.println(ipPeer+":"+portPeer);
					tracker.addPeer(new Peer(ipPeer, portPeer));
				}
			}
		}		
	}

	public static void main(String[] args) {

		/*String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
        data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");*/

		String url = "bttracker.debian.org:6969/announce?";		
		String request = "info_hash=x%60%a0tkm%c4%d0%be%11%5b%c9%7d%bdA%3b%3d%27%84%01&peer_id=-TR2130-n12r35yy9y17&port=51413&uploaded=0&downloaded=0&left=679477248&numwant=80&key=duzwhmd8&compact=1&supportcrypto=0&event=started";


	}
}
